<?php

namespace app\modules\setting\controllers\yjrwsz;

use app\common\service\KaiGuan;
use Yii;
use app\modules\setting\models\yjrwsz\EtcKg;
use app\modules\setting\configs\yjrwsz\XtkgConfig;
use app\modules\setting\models\yjrwsz\EtcKgSearch;
use sookie\react\AdminController;
use yii\helpers\ArrayHelper;
use yii\helpers\Json;
use yii\base\Exception;
use sookie\excel\SaveExcel;
use sookie\db\DBHandler;


/**
 * XtkgController implements the CRUD actions for EtcKg model.
 */
class XtkgController extends AdminController
{
    /**
    * @return array
    * 列表数据
    */
    public function actionIndex()
    {
        try {
            $searchModel = new EtcKgSearch();
            $dataProvider = $searchModel->search(Yii::$app->request->queryParams);
            $data = $dataProvider->getModels();
            if($data){
                $data = array_map(function($item){
                    $item = $item->toArray();
                    $item['status'] = empty($item['status']) ? '已停止':'运行中';
                    return $item;
                },$data);
            }
            return ArrayHelper::merge(["data" => $data, "pagination" => $dataProvider->getPagination()],XtkgConfig::configIndex());
        }catch (\Throwable $e){
            return ["ok" => false,"msg" => $e->getMessage(),"code" => 401];
        }
    }


    public function actionOpen($id){
        try {

            $model = $this->findModel($id);
            $obj_kg  = new KaiGuan();
            $ok = $obj_kg->OpenKG($model->kg_str);

            if ($ok) {
                return ["msg" => "开启全局开关成功"];
            }else{
                throw new Exception("开启全局开关失败。");
            }
        }catch (\Throwable $e){
            return ["ok" => false,"msg" => $e->getMessage(),"code" => 401];
        }
    }

    public function actionClose($id){
        try {
            $model = $this->findModel($id);
            $obj_kg  = new KaiGuan();
            $ok = $obj_kg->CloseKG($model->kg_str);

            if ($ok) {
                return ["msg" => "关闭全局开关成功"];
            }else{
                throw new Exception("关闭全局开关失败。");
            }

        }catch (\Throwable $e){
            return ["ok" => false,"msg" => $e->getMessage(),"code" => 401];
        }
    }




    protected function findModel($id)
    {
        if (($model = EtcKg::findOne($id)) !== null) {
            return $model;
        }

        throw new Exception('不存在的记录');
    }




}

